package com.yuelan.codelib.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

import org.apache.http.util.EncodingUtils;

import android.content.Context;

/**
 * class name：FileService<BR>
 * class description：android文件的一些读取操作<BR>
 * PS： <BR>
 * 
 * @version 1.00 2010/10/21
 * @author CODYY)peijiangping
 */
public class FileUtil {
	// 读取sd中的文件
	public static String readSDCardFile(String path) {
		File file = new File(path);
		FileInputStream fis = null;
		String result = null;
		try {
			fis = new FileInputStream(file);
			result = streamRead(fis);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;

	}

	// 在res目录下建立一个raw资源文件夹，这里的文件只能读不能写入。。。
	public String readRawFile(int fileId, Context c) {
		InputStream is = null;
		String result = null;
		try {
			is = c.getResources().openRawResource(fileId);
			result = streamRead(is);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;

	}

	private static String streamRead(InputStream is) throws IOException {
		int buffersize = is.available();// 取得输入流的字节长度
		byte buffer[] = new byte[buffersize];
		is.read(buffer);// 将数据读入数组
		is.close();// 读取完毕后要关闭流。
		String result = EncodingUtils.getString(buffer, "UTF-8");// 设置取得的数据编码，防止乱码
		return result;
	}

	// 在assets文件夹下的文件，同样是只能读取不能写入
	public static String readAssetsFile(String filename, Context c) {
		InputStream is = null;
		String result = null;
		try {
			is = c.getResources().getAssets().open(filename);
			result = streamRead(is);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	/**
	 * 作用：将buffer写入文件<BR>
	 * true继续写，false 重新写 作者：peijiangping<BR>
	 * 日期：2012-6-28
	 */
	public static void writeSDCardFile(String path, byte[] buffer, boolean can) {
		File file = new File(path);
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file, can);
			fos.write(buffer);
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 作用：删除文件或者文件夹mode=1全部删除，mode=2保留最外面的文件夹<BR>
	 * 作者：peijiangping<BR>
	 * 日期：2012-6-28
	 */
	public boolean deleteFile(File file, int mode) {
		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
			} else if (file.isDirectory()) { // 否则如果它是一个目录
				File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
				for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
					this.deleteFile(files[i], 1); // 把每个文件 用这个方法进行迭代
				}
				if (mode == 1) {
					file.delete();
				}
			}
		} else {
			return false;
		}
		return true;
	}

	public static void writeDateFile(String filename, byte[] buffer, Context c) {
		FileOutputStream fos = null;
		try {
			fos = c.openFileOutput(filename, Context.MODE_PRIVATE);
			fos.write(buffer);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * copy文件
	 * 
	 * @param from
	 * @param to
	 * @return
	 */
	public static boolean copyFile(File from, File to) {
		try {
			FileInputStream fis = new FileInputStream(from);
			FileOutputStream fos = new FileOutputStream(to);
			byte buffer[] = new byte[1024];
			int count = 0;
			while ((count = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, count);
			}
			fos.close();
			fis.close();
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	// 读取应用的data/data的files目录下文件数据
	public static String readDateFile(String fileName, Context c) {
		FileInputStream fis = null;
		String result = null;
		try {
			fis = c.openFileInput(fileName);
			result = streamRead(fis);
		} catch (IOException e) {
//			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public static String getFileMD5(File file) {
		if (!file.exists() || !file.isFile()) {
			return null;
		}
		MessageDigest digest = null;
		FileInputStream in = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			digest = MessageDigest.getInstance("MD5");
			in = new FileInputStream(file);
			while ((len = in.read(buffer, 0, 1024)) != -1) {
				digest.update(buffer, 0, len);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		BigInteger bigInt = new BigInteger(1, digest.digest());
		return bigInt.toString(16);
	}
}